/**
 * MainActivity.java
 * @author Marco Secchiero
 * 
 * This is the first Activity called when the application starts.
 * It creates a connection with the server and then launches MenuViewActivity
 * 
 */

package wfta.client.gui;

import wfta.client.ManagerStaticBuilder;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private static final int MENU_CONNECT = 0;
	private static final int ERROR_DIALOG = 0;

		
	/**
	 * Dialog's button OnClickListener
	 * @author Marco Secchiero
	 *
	 */
	protected class OKListener implements OnClickListener {
		private Dialog dialog;
		
		public OKListener(Dialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			dialog.dismiss();
		}
	}
    
	protected Dialog onCreateDialog(int id) {
		switch(id){
		case ERROR_DIALOG:
			Dialog dialog = new Dialog(this);
			dialog.setContentView(wfta.client.R.layout.dialog);
			dialog.setTitle("Error!");
			// creates the button and assignes it to the dialog
			Button okBtn = (Button) dialog.findViewById(wfta.client.R.id.button);
			okBtn.setText("Ok");
			okBtn.setOnClickListener(new OKListener(dialog));
			
			TextView messages = (TextView) dialog.findViewById(wfta.client.R.id.text);
			messages.setText("Connection Lost!");
			return dialog;
		default: 
			return null;	
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
               
			TextView welcome = new TextView(this);
			welcome.setText("Welcome to WiFi Take away!");
			setContentView(welcome);

		} catch (Exception e) {
			showDialog(ERROR_DIALOG);
		}
	}
	
	/**
	 * Create a menu
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_CONNECT, 0, "Connect");
		return true;
	}
	
	/**
	 * Actions starting by menu item selection
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case MENU_CONNECT:
			try {
				// tries to establish a connection with the server
				ManagerStaticBuilder.CreateConnection(this);
				// creates an intent for a new Activity and starts it (MenuViewActivity)
				Intent intent = new Intent(this,wfta.client.gui.MenuViewActivity.class);
				startActivity(intent);
				finish();
				return true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				showDialog(ERROR_DIALOG);
			}
		}
		return false;
	}
}
